package com.ncu.cloundeoffice.config.filter;


import com.ncu.cloundeoffice.pojo.TMenu;
import com.ncu.cloundeoffice.pojo.TRole;
import com.ncu.cloundeoffice.service.TMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.security.Security;
import java.util.Collection;
import java.util.List;

/**
 * 权限控制'
 * 根据请求url分析用户所需的角色
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private TMenuService tMenuService;
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获取请求的URL
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        System.out.println(requestUrl);
        //获取所有的菜单和对应的权限
        List<TMenu> menuWithRole = tMenuService.getMenuWithRole();
        //遍历   将与匹配上的路径的角色存放在SecurityConfig.createList()中
        for (TMenu tMenu : menuWithRole) {
            if(antPathMatcher.match(tMenu.getUrl(),requestUrl)){
                //所在菜单下的全部角色
                List<TRole> roles = tMenu.getRoles();
                String[] str = new String[roles.size()];
                for(int i = 0 ; i < tMenu.getRoles().size(); i++){
                    str[i] = roles.get(i).getName();
                }
                return SecurityConfig.createList(str);
            }
        }
        //没有匹配的url默认登录即可访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
